package com.example.iwalk.newprintapplication.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.iwalk.newprintapplication.R;
import com.example.iwalk.newprintapplication.adapter.IpAddressAdapter;
import com.example.iwalk.newprintapplication.imp.BlueToothSocket;
import com.example.iwalk.newprintapplication.imp.NetSocket;
import com.example.iwalk.newprintapplication.imp.OperatorImp;
import com.example.iwalk.newprintapplication.imp.Printer58Imp;
import com.example.iwalk.newprintapplication.inter.AdapterButtonClickListener;
import com.example.iwalk.newprintapplication.inter.IpCatcher;
import com.example.iwalk.newprintapplication.inter.Operator;
import com.example.iwalk.newprintapplication.inter.Printer;
import com.example.iwalk.newprintapplication.inter.SocketInter;
import com.example.iwalk.newprintapplication.inter.SocketStateChangeListener;
import com.example.iwalk.newprintapplication.util.IpCatchThread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_0;
import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_1;
import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_2;
import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_3;
import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_4;
import static com.example.iwalk.newprintapplication.constant.SocketState.ERROR_5;
import static com.example.iwalk.newprintapplication.constant.SocketState.STATE_1;
import static com.example.iwalk.newprintapplication.constant.SocketState.STATE_2;
import static com.example.iwalk.newprintapplication.constant.SocketState.STATE_3;
import static com.example.iwalk.newprintapplication.constant.SocketState.STATE_4;
import static com.example.iwalk.newprintapplication.constant.SocketState.STATE_5;


public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterButtonClickListener {

    private Button button1, button2, button3;
    private TextView tv_ip, tv_printer_info, tv_socket_info;
    private ListView lv_ip_address;
    private List<String> ipAddresses;
    private IpAddressAdapter adapter;
    private Button btn_next_page;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1 = ((Button) findViewById(R.id.button1));
        button2 = ((Button) findViewById(R.id.button2));
        button3 = ((Button) findViewById(R.id.button3));
        btn_next_page = ((Button) findViewById(R.id.btn_next_page));
        tv_ip = ((TextView) findViewById(R.id.text));
        tv_socket_info = ((TextView) findViewById(R.id.tv_socket_info));
        tv_printer_info = ((TextView) findViewById(R.id.tv_printer_info));
        lv_ip_address = ((ListView) findViewById(R.id.listview));
        ipAddresses = new ArrayList<>();
        adapter = new IpAddressAdapter(ipAddresses, this);
        adapter.setListener(this);
        lv_ip_address.setAdapter(adapter);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
        btn_next_page.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_next_page:
                startActivity(new Intent(this, PrintActivity.class));
                break;
            case R.id.button1:
                NetPrintThreadStart("192.168.31.222");
                break;
            case R.id.button2:
                SocketInter socketInter = new BlueToothSocket(this, stateChangeListener);
                Printer printer = new Printer58Imp();
                Operator operator = new OperatorImp();
                printer.print(socketInter.getSocketOut(), operator.sendData(), stateChangeListener);
                socketInter.close();
                break;
            case R.id.button3://获取局域网内可用打印机ip地址
                String localHostIp = NetSocket.getLocalHostIp();
                tv_ip.setText(localHostIp);
                new IpCatchThread(localHostIp, new IpCatcher() {
                    @Override
                    public void onCatchStart() {
                        lv_ip_address.post(new Runnable() {
                            @Override
                            public void run() {
                                button3.setText("正在获取打印机列表");
                                ipAddresses.clear();
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }

                    @Override
                    public void onIpCatched(final String ipAddress) {
                        lv_ip_address.post(new Runnable() {
                            @Override
                            public void run() {
                                ipAddresses.add(ipAddress);
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }

                    @Override
                    public void onCatchFinish() {
                        button3.post(new Runnable() {
                            @Override
                            public void run() {
                                button3.setText("打印机列表获取完毕");
                            }
                        });
                    }
                }).start();
                break;
        }
    }

    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 11:
                    String printerInfo = (String) msg.obj;
                    tv_printer_info.setText(printerInfo);
                    break;
            }
        }
    };

    SocketStateChangeListener stateChangeListener = new SocketStateChangeListener() {
        @Override
        public void onStateChanged(final int state) {
            tv_socket_info.post(new Runnable() {
                @Override
                public void run() {
                    switch (state) {
                        case STATE_1:
                            tv_socket_info.setText("正在创建Socket连接");
                            break;
                        case STATE_2:
                            tv_socket_info.setText("正在获取输出流");
                            break;
                        case STATE_3:
                            tv_socket_info.setText("正在写入测试页面数据");
                            break;
                        case STATE_4:
                            tv_socket_info.setText("正在关闭输出流");
                            break;
                        case STATE_5:
                            tv_socket_info.setText("正在获取输入流");
                            break;
                    }
                }
            });
        }

        @Override
        public void onConnectFailed(final int error) {
            tv_socket_info.post(new Runnable() {
                @Override
                public void run() {
                    switch (error) {
                        case ERROR_0:
                            tv_socket_info.setText("必要参数不能为空");
                            break;
                        case ERROR_1:
                            tv_socket_info.setText("创建Socket失败");
                            break;
                        case ERROR_2:
                            tv_socket_info.setText("获取输出流失败");
                            break;
                        case ERROR_3:
                            tv_socket_info.setText("写入测试页面数据失败");
                            break;
                        case ERROR_4:
                            tv_socket_info.setText("关闭Socket出错");
                            break;
                        case ERROR_5:
                            tv_socket_info.setText("获取输出流失败");
                            break;
                    }
                }
            });
        }
    };

    private void NetPrintThreadStart(final String host) {
        new Thread(new Runnable() {
            int i = 0;

            @Override
            public void run() {
                SocketInter socketInter =
                        new NetSocket(host, 9100, stateChangeListener);
                Printer printer = new Printer58Imp();
                Operator operator = new OperatorImp("gb2312");
//                printer.print(socketInter.getSocketOut(), operator.getPrinterInfo(), stateChangeListener);
                printer.print(socketInter.getSocketOut(), operator.sendData(), stateChangeListener);
//                Log.e("sdsdf", "(socketInter.getSocketOut");
//                InputStream inputStream = socketInter.getSocketIn();
//                Log.e("sdsdf", "socketInter.getSocketIn");
//                while (true) {
//                    try {
//                        String s = inputStream2String(inputStream);
//                        Message msg = handler.obtainMessage();
//                        msg.what = 11;
//                        msg.obj = s;
//                        handler.sendMessage(msg);
//                        if (!s.equals("")) {
//                            break;
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
                socketInter.close();
            }
        }).start();
    }

    /**
     * 将InputStream转换成String
     *
     * @param is InputStream
     * @return String
     * @throws Exception
     */
    private String inputStream2String(InputStream is) {
        StringBuffer s = new StringBuffer();
        try {
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            Log.e("sdsdf", "1");
            String data;
            try {
                Log.e("sdsdf", bufferedReader.readLine());
                while ((data = bufferedReader.readLine()) != null) {
                    s.append(data);
                    Log.e("sdsdf", "2");
                }
                Log.e("sdsdf", "3");
            } catch (IOException e) {
                Log.e("sdsdf", "inputStream2String", e);
                e.printStackTrace();
            }
        } catch (IOException e) {
            Log.e("sdsdf", "utf-8(", e);
            e.printStackTrace();
        }
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s.toString();
    }

    /**
     * 将InputStream转换成String
     *
     * @param is InputStream
     * @return String
     * @throws Exception
     */
    private String dataInputStream2String(InputStream is) {
        StringBuffer s = new StringBuffer();
        try {
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            String data;
            try {
                while ((data = bufferedReader.readLine()) != null)
                    s.append(data);
                Log.e("sdsdf", data);
            } catch (IOException e) {
                Log.e("sdsdf", "inputStream2String", e);
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s.toString();
    }

    @Override
    public void onButtonClick(int position, View view) {
        NetPrintThreadStart(ipAddresses.get(position));
    }
}
